package com.dongdongshop.service.impl;

import com.dongdongshop.mapper.TbOrderItemMapper;
import com.dongdongshop.mapper.TbOrderMapper;
import com.dongdongshop.pojo.TbOrder;
import com.dongdongshop.pojo.TbOrderExample;
import com.dongdongshop.pojo.TbOrderItem;
import com.dongdongshop.pojo.TbOrderItemExample;
import com.dongdongshop.service.CartService;
import com.dongdongshop.service.OrderService;
import com.dongdongshop.vo.Cart;
import com.dongdongshop.vo.OrderNumVO;
import com.dongdongshop.vo.OrderVO;
import com.dongdongsop.constant.CartConstant;
import com.dongdongshop.util.IdWorker;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@DubboService
public class OrderServiceImpl implements OrderService {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private TbOrderItemMapper orderItemMapper;

    @Resource
    private TbOrderMapper orderMapper;

    @DubboReference
    private CartService cartService;

    @Autowired
    private IdWorker idWorker;

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Override
    @Transactional
    public Map<String,String> submitOrder(TbOrder order, Long id) {
        List<Cart> cartList = cartService.selectCartListFromRedis(id);
        Double WIDtotal_amount = 0.0;
        StringBuilder WIDsubject = new StringBuilder();
        Long order_num = idWorker.nextId();
        for (Cart cart : cartList) {
            Long orderId = idWorker.nextId();
            TbOrder tbOrder = new TbOrder();//创建新的对象
            tbOrder.setOrderId(orderId);//订单ID
            tbOrder.setUserId(order.getUserId());// 用户名
            tbOrder.setPaymentType(order.getPaymentType());//支付类型
            tbOrder.setStatus("1");//状态：未付款
            tbOrder.setReceiverAreaName(order.getReceiverAreaName());//地址
            tbOrder.setReceiverMobile(order.getReceiverMobile());//手机号
            tbOrder.setReceiver(order.getReceiver());//收货人
            tbOrder.setSourceType("2");//订单来源
            tbOrder.setSellerId(cart.getSellerId());//商家ID
            tbOrder.setOrderNum(order_num.toString());
            //循环购物车明细
            double money = 0;
            List<TbOrderItem> orderItemList = cart.getOrderItemList();
            for (TbOrderItem orderItem : orderItemList) {
                WIDsubject.append(orderItem.getTitle());
                orderItem.setId(idWorker.nextId());
                orderItem.setOrderId(orderId);//订单ID
                orderItem.setSellerId(cart.getSellerId());
                money+=orderItem.getTotalFee().doubleValue();//金额累加
                orderItem.setOrderNum(order_num.toString());
                orderItem.setStatus("1");
                orderItemMapper.insertSelective(orderItem);
            }
            tbOrder.setPayment(new BigDecimal(money));
            orderMapper.insert(tbOrder);
            //累加总钱数
            WIDtotal_amount += money;
        }
        Map<String,String> map = new HashMap<>();
        map.put("WIDout_trade_no",order_num.toString());
        map.put("WIDtotal_amount",WIDtotal_amount.toString());
        map.put("WIDsubject",WIDsubject.toString());
        map.put("WIDbody","用户使用支付宝进行付款");
        cartService.deleteCartListFromRedis(id);
        return map;
    }

    @Override
    public boolean updateByOrderNum(String out_trade_no, String trade_no,String status) {
        TbOrderExample example = new TbOrderExample();
        TbOrderExample.Criteria criteria = example.createCriteria();
        criteria.andOrderNumEqualTo(out_trade_no);
        List<TbOrder> tbOrders = orderMapper.selectByExample(example);
        int i = 0;
        for (TbOrder order : tbOrders) {
            order.setStatus(status);
            order.setTradeNo(trade_no);
            i = orderMapper.updateByPrimaryKeySelective(order);
        }

        TbOrderItemExample example1 = new TbOrderItemExample();
        TbOrderItemExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andOrderNumEqualTo(out_trade_no);
        List<TbOrderItem> tbOrderItems = orderItemMapper.selectByExample(example1);
        for (TbOrderItem orderItem : tbOrderItems) {
            orderItem.setTrabeNum(trade_no);
            orderItem.setStatus(status);
            orderItemMapper.updateByPrimaryKeySelective(orderItem);
        }
        return i>0;
    }

    @Override
    public List<OrderVO> getInfoByUserId(String username) {
        TbOrderExample example = new TbOrderExample();
        TbOrderExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(username);
        criteria.andStatusEqualTo("2");
        List<TbOrder> list = orderMapper.selectByExample(example);
        List<OrderVO> orderVOList = new ArrayList<>();
        list.forEach(order -> {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order,orderVO);
            List<TbOrderItem> orderItemList = orderItemMapper.selectByOrderIdAndStatus(order.getOrderId());
            if (orderItemList.size() != 0){
                orderVO.setOrderItemList(orderItemList);
                orderVOList.add(orderVO);
            }
        });
        return orderVOList;
    }

    @Override
    public boolean removeById(long itemId) {
        return orderItemMapper.removeById(itemId);
    }

    @Override
    public List<TbOrderItem> selectAll(String out_trade_no) {
        TbOrderItemExample example = new TbOrderItemExample();
        TbOrderItemExample.Criteria criteria = example.createCriteria();
        criteria.andOrderNumEqualTo(out_trade_no);
        criteria.andSellerIdEqualTo("2");
        return orderItemMapper.selectByExample(example);
    }

    @Override
    public boolean updateByStatus(String out_trade_no) {
        return orderItemMapper.updateByStatus(out_trade_no);
    }

    @Override
    public boolean updateByOrderNumAndStatus(String out_trade_no) {
        orderMapper.updateByOrderNumAndStatus(out_trade_no);
        return orderItemMapper.updateByOrderNumAndStatus(out_trade_no);
    }

    @Override
    public TbOrder getOrderNum(String orderNum) {
        return orderMapper.getOrderNum(orderNum);
    }

    @Override
    public void getMQ(OrderNumVO numVO) {
        Message<OrderNumVO> message = MessageBuilder.withPayload(numVO).build();
        rocketMQTemplate.sendMessageInTransaction("order-score", message, numVO);
    }

}
